<?php
/**
*
* @author Blackpawn blackpawn666@hotmail.com - http://blackpawnsarchives.net
* @co_author GameCharmer admin@gamecharmer.com - http://gaming.gamecharmer.com
* @package Age of Dragons Mod :: ( Game Console Required )
* @version $Id: functions.php 1.1.1 12-26-2009 Blackpawn
* @copyright (c) 2009 Blackpawns Archives
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* @ignore
*/
if (!defined('AOD'))
{
	exit;
}

function shop_add_resource($sql_quest_ary)
{
	global $db;

	$sql = 'INSERT INTO ' . AOD_SHOP_TABLE .' ' . $db->sql_build_array('INSERT', $sql_quest_ary);
	$db->sql_query($sql);	
}

function bm_add_resource($sql_quest_ary)
{
	global $db;

	$sql = 'INSERT INTO ' . AOD_BLACKMARKET_TABLE .' ' . $db->sql_build_array('INSERT', $sql_quest_ary);
	$db->sql_query($sql);	
}

function delete_shop_resource($rid)
{
	global $db;
	$sql = "DELETE FROM " . AOD_SHOP_TABLE . " 
	WHERE id = $rid"; 	  
	$db->sql_query($sql);	
}

function delete_bm_resource($rid)
{
	global $db;
	$sql = "DELETE FROM " . AOD_BLACKMARKET_TABLE . " 
	WHERE id = $rid"; 	  
	$db->sql_query($sql);	
}

function build_field_option_list()
{
	global $db, $aod_config;
	$field_options = Null;
	
		$sql = "SELECT * 
		FROM " . AOD_FIELDS_TABLE."";
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$field_options .= '<option value="'.$row['field'].'">'.$row['field'].'</option>';
		}	
		$db->sql_freeresult($result);

		
		return $field_options;
}

function build_unit_option_list()
{
	global $db, $aod_config;
	$unit_options = Null;
	
		$sql = "SELECT * 
		FROM " . AOD_UNITS_TABLE." WHERE id > 1";
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$unit_options .= '<option value="'.$row['id'].'">'.$row['unit_name'].'</option>';
		}	
		$db->sql_freeresult($result);

		
		return $unit_options;
}

function build_building_option_list()
{
	global $db, $aod_config;
	$building_options = Null;
	
		$sql = "SELECT * 
		FROM " . AOD_BUILDINGS_TABLE."";
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$building_options .= '<option value="'.$row['id'].'">'.$row['building_name'].'</option>';
		}	
		$db->sql_freeresult($result);

		
		return $building_options;
}

function disapprove_quest($qid)
{
	global $db;
	$sql = "UPDATE " . AOD_QUESTS_TABLE . "
	SET quest_approved = 0 
	WHERE id = $qid"; 	  
	$db->sql_query($sql);	
}

function approve_quest($qid)
{
	global $db;
	$sql = "UPDATE " . AOD_QUESTS_TABLE . "
	SET quest_approved = 1 
	WHERE id = $qid"; 	  
	$db->sql_query($sql);	
}

function delete_quest($qid)
{
	global $db;
	$sql = "DELETE FROM " . AOD_QUESTS_TABLE . " 
	WHERE id = $qid"; 	  
	$db->sql_query($sql);	
}

function add_quest($sql_quest_ary)
{
	global $db;

	$sql = 'INSERT INTO ' . AOD_QUESTS_TABLE .' ' . $db->sql_build_array('INSERT', $sql_quest_ary);
	$db->sql_query($sql);	
}

function build_player_option_list($showadmins = FALSE)
{
	global $db, $aod_config;
		
		$player_options = NULL;
		
		if($showadmins){
			$sql = "SELECT * 
			FROM " . AOD_KINGDOMS_TABLE."";
			$result = $db->sql_query($sql);

			while ($row = $db->sql_fetchrow($result))
			{
				$player_options .= '<option value="'.$row['user_id'].'">'.$row['kingdom_ruler'].' of '.$row['kingdom_name'].'</option>';
			}	
			$db->sql_freeresult($result);
		}else{
			$sql = "SELECT * 
			FROM " . AOD_KINGDOMS_TABLE."
			WHERE admin_access = 0 AND user_id <> 2";
			$result = $db->sql_query($sql);
	
			while ($row = $db->sql_fetchrow($result))
			{
				$player_options .= '<option value="'.$row['user_id'].'">'.$row['kingdom_ruler'].' of '.$row['kingdom_name'].'</option>';
			}	
			$db->sql_freeresult($result);	
		}
		
		return $player_options;
}

function set_aod_config($config_name, $config_value)
{
	global $db, $aod_config;

	$sql = 'UPDATE ' . AOD_CONFIG_TABLE . "
		SET config_value = '" . $db->sql_escape($config_value) . "'
		WHERE config_name = '" . $db->sql_escape($config_name) . "'";
	$db->sql_query($sql);

	if (!$db->sql_affectedrows() && !isset($aod_config[$config_name]))
	{
		$sql = 'INSERT INTO ' . AOD_CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
			'config_name'	=> $config_name,
			'config_value'	=> $config_value));
		$db->sql_query($sql);
	}

	$aod_config[$config_name] = $config_value;
}

function delete_game_news($nid)
{
	global $db;
	$sql = "DELETE FROM " . AOD_NEWS_TABLE . " 
	WHERE id = $nid"; 	  
	$db->sql_query($sql);	
	
}

function post_game_news($news,$user_id,$date)
{
	global $db;
	
	$sql = 'INSERT INTO ' . AOD_NEWS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'	=> $user_id,
		'news' 	=> $news,
		'date' 	=> $date,
		)
	);		  
	$db->sql_query($sql);	
}

function count_kingdom_news($user_id)
{
	global $db;
	$total = 0;

	$sql = "SELECT count(*) as total 
	FROM " . AOD_KINGDOM_NEWS_TABLE . "
	WHERE user_id = $user_id";
	$result = $db->sql_query($sql);
	while ($row = $db->sql_fetchrow($result))
	{
		$total = $row['total'];
	}
	
	return $total;
}

function exp_to_next_level($kingdom_level)
{	
	$base_exp = 15;
	$exp_per_lvl_addon = floor($kingdom_level * $base_exp);
	
	$tnl = (($kingdom_level * 50) + $exp_per_lvl_addon);
  
	return floor($tnl);
}

function calc_exp($enemy_level, $kingdom_level)
{

	$exp_win_1 = $enemy_level * 6;
	
	$exp_win_2 = (($kingdom_level - $enemy_level) > 0) ? $exp_win_1 - (($kingdom_level - $enemy_level) * 3) : $exp_win_1 + (($kingdom_level - $enemy_level) * 3);
	
	$exp_win_2 = ($exp_win_2 <= 0) ? 1 : $exp_win_2;
	
	$exp_win_3 = round(0.75 * $exp_win_2);
	
	$exp_gain = ceil(rand($exp_win_3, $exp_win_2));

	// Maximum Exp Gained
    if($exp_gain > 100)
	{
		$exp_gain = 100;
	}
	
	// Minimum Exp Gained
    if($exp_gain < 1)
	{
		$exp_gain = 1;
	}	
	
	return floor($exp_gain);
}

function count_kingdoms()
{
	global $db;
	$total = 0;

	$sql = 'SELECT count(*) as total 
	FROM ' . AOD_KINGDOMS_TABLE . '';
	$result = $db->sql_query($sql);
	while ($row = $db->sql_fetchrow($result))
	{
		$total = $row['total'];
	}
	
	return $total;
}

function fetch_total_land($user_id)
{
	global $db,$user;

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());	
	}
		
	$king = fetch_kingdom_data($user_id);
	$buildings = fetch_kingdom_building_counts($user_id);
	
	$total = (
	$buildings[1] +
	$buildings[2] +
	$buildings[3] +
	$buildings[4] +
	$buildings[5] +
	$buildings[6] +
	$buildings[7] +
	$buildings[8] +
	$buildings[9] +
	$king['kingdom_land']);
	
	return $total;
}

function fetch_kingdom_building_levels($user_id)
{
	global $db,$user;

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());	
	}else{
		
		$sql = "SELECT * 
		FROM " . AOD_KINGDOMS_TABLE . "
		WHERE user_id = $user_id";
		$result = $db->sql_query($sql);
	
		if($row = $db->sql_fetchrow($result))
		{
		
			$unit = array(
				'1' 	=> $row['kingdom_farms_lvl'],
				'2' 	=> $row['kingdom_timber_mills_lvl'],
				'3' 	=> $row['kingdom_iron_mines_lvl'],
				'4' 	=> $row['kingdom_gold_mines_lvl'],
				'5'		=> $row['kingdom_towers_lvl'],
				'6' 	=> $row['kingdom_granaries_lvl'],
				'7' 	=> $row['kingdom_woodsheds_lvl'],
				'8' 	=> $row['kingdom_ironpits_lvl'],
				'9' 	=> $row['kingdom_vaults_lvl'],
			);  		
		}	
		$db->sql_freeresult($result);
	
		return $unit;	
	}
}

function fetch_kingdom_building_counts($user_id)
{
	global $db,$user;

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());	
	}else{
		
		$sql = "SELECT * 
		FROM " . AOD_KINGDOMS_TABLE . "
		WHERE user_id = $user_id";
		$result = $db->sql_query($sql);
	
		if($row = $db->sql_fetchrow($result))
		{
		
			$unit = array(
				'1' 	=> $row['kingdom_farms'],
				'2' 	=> $row['kingdom_timber_mills'],
				'3' 	=> $row['kingdom_iron_mines'],
				'4' 	=> $row['kingdom_gold_mines'],
				'5'		=> $row['kingdom_towers'],
				'6' 	=> $row['kingdom_granaries'],
				'7' 	=> $row['kingdom_woodsheds'],
				'8' 	=> $row['kingdom_ironpits'],
				'9' 	=> $row['kingdom_vaults'],
			);  		
		}	
		$db->sql_freeresult($result);
	
		return $unit;	
	}
}

function fetch_kingdom_unit_counts($user_id)
{
	global $db,$user;

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());	
	}else{
		
		$sql = "SELECT * 
		FROM " . AOD_KINGDOMS_TABLE . "
		WHERE user_id = $user_id";
		$result = $db->sql_query($sql);
	
		if($row = $db->sql_fetchrow($result))
		{
		
			$unit = array(
				'1' 	=> $row['kingdom_villagers'],
				'2' 	=> $row['kingdom_soldiers'],
				'3' 	=> $row['kingdom_spies'],
				'4' 	=> $row['kingdom_macemen'],
				'5'		=> $row['kingdom_axemen'],
				'6' 	=> $row['kingdom_spearmen'],
				'7' 	=> $row['kingdom_swordsmen'],
				'8' 	=> $row['kingdom_legionnaires'],
				'9' 	=> $row['kingdom_knights'],
				'10'	=> $row['kingdom_slingers'],
				'11' 	=> $row['kingdom_bowmen'],
				'12' 	=> $row['kingdom_long_bowmen'],
				'13' 	=> $row['kingdom_crossbowmen'],
				'14' 	=> $row['kingdom_light_sword_cavalry'],
				'15' 	=> $row['kingdom_heavy_sword_cavalry'],
				'16' 	=> $row['kingdom_light_archer_cavalry'],
				'17' 	=> $row['kingdom_heavy_archer_cavalry'],
				'18' 	=> $row['kingdom_paladin'],
				'19' 	=> $row['kingdom_dragon_knights'],
				'20' 	=> $row['kingdom_rams'],
				'21' 	=> $row['kingdom_catapults'],
				'22' 	=> $row['kingdom_heavy_catapults'],
				'23' 	=> $row['kingdom_ballistas'],
				'24' 	=> $row['kingdom_trebuchets'],
				'25' 	=> $row['kingdom_chimeras'],
				'26' 	=> $row['kingdom_hydras'],
				'27' 	=> $row['kingdom_basilisks'],
				'28' 	=> $row['kingdom_wyverns'],
				'29' 	=> $row['kingdom_leviathans'],
				'30' 	=> $row['kingdom_dragons'],
			);  		
		}	
		$db->sql_freeresult($result);
	
		return $unit;	
	}
}

function build_list($data)
{
	$count = count($data);
	
	if ($count > 0) 
	{
		while (list($num,$msg) = each ($data)) 
		{
			$i++;
			if ($i == $count && $i != 1){
				$newdata = $newdata . " and <b>$msg</b>. ";
			}elseif ($i == $count && $i == 1){
				$newdata = $newdata . "<b>$msg</b>. ";
			}else{
				$newdata = $newdata . " <b>$msg</b>";
				
				if ($i+1 != $count){
					$newdata = $newdata . ",";
				}
			}
		}
	}
	
	return $newdata;	
}

function build_sql_list($data)
{
	$count = count($data);
	
	if ($count > 0) 
	{
		while (list($num,$amount) = each ($data)) 
		{
			$i++;
			if ($i == $count && $i != 1){
				$newdata = $newdata . " , $amount ";
			}elseif ($i == $count && $i == 1){
				$newdata = $newdata . "$amount";
			}else{
				$newdata = $newdata . " $amount";
				
				if ($i+1 != $count){
					$newdata = $newdata . ",";
				}
			}
		}
	}
	
	return 	$newdata;
}

function set_kingdom_stats($user_id)
{
	global $db,$user;
	
	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());
	}
	
	$king = fetch_kingdom_data($user_id);

	// Other
	$kingdom_level = $king['kingdom_level'];
	$kingdom_exp = $king['kingdom_exp'];
	$kingdom_off_bonus = $king['kingdom_off_bonus'];
	$kingdom_def_bonus = $king['kingdom_def_bonus'];
	$kingdom_land = $king['kingdom_land'];
	$kingdom_gold = $king['kingdom_gold'];
	$kingdom_food = $king['kingdom_food'];
	$kingdom_wood = $king['kingdom_wood'];
	$kingdom_iron = $king['kingdom_iron'];
	
	// Units
	$kingdom_villagers = $king['kingdom_villagers'];
	$kingdom_soldiers = $king['kingdom_soldiers'];
	$kingdom_spies = $king['kingdom_spies'];
	$kingdom_macemen = $king['kingdom_macemen'];
	
	$kingdom_axemen = $king['kingdom_axemen'];
	$kingdom_spearmen = $king['kingdom_spearmen'];
	$kingdom_swordsmen = $king['kingdom_swordsmen'];
	$kingdom_legionnaires = $king['kingdom_legionnaires'];
	$kingdom_knights = $king['kingdom_knights'];
	$kingdom_slingers = $king['kingdom_slingers'];
	$kingdom_bowmen = $king['kingdom_bowmen'];
	$kingdom_long_bowmen = $king['kingdom_long_bowmen'];
	$kingdom_crossbowmen = $king['kingdom_crossbowmen'];
	$kingdom_light_sword_cavalry = $king['kingdom_light_sword_cavalry'];
	$kingdom_heavy_sword_cavalry = $king['kingdom_heavy_sword_cavalry'];
	$kingdom_light_archer_cavalry = $king['kingdom_light_archer_cavalry'];
	$kingdom_heavy_archer_cavalry = $king['kingdom_heavy_archer_cavalry'];
	$kingdom_paladin = $king['kingdom_paladin'];
	$kingdom_dragon_knights = $king['kingdom_dragon_knights'];
	$kingdom_rams = $king['kingdom_rams'];
	$kingdom_catapults = $king['kingdom_catapults'];
	$kingdom_heavy_catapults = $king['kingdom_heavy_catapults'];
	$kingdom_ballistas = $king['kingdom_ballistas'];
	$kingdom_trebuchets = $king['kingdom_trebuchets'];
	$kingdom_chimeras = $king['kingdom_chimeras'];
	$kingdom_hydras = $king['kingdom_hydras'];
	$kingdom_basilisks = $king['kingdom_basilisks'];
	$kingdom_wyverns = $king['kingdom_wyverns'];
	$kingdom_leviathans = $king['kingdom_leviathans'];
	$kingdom_dragons = $king['kingdom_dragons'];
	
	// Buildings
	$kingdom_farms = $king['kingdom_farms'];
	$kingdom_timber_mills = $king['kingdom_timber_mills'];
	$kingdom_iron_mines = $king['kingdom_iron_mines'];
	$kingdom_gold_mines = $king['kingdom_gold_mines'];
	$kingdom_towers = $king['kingdom_towers'];
	$kingdom_towers_lvl = $king['kingdom_towers_lvl'];
	$kingdom_granaries = $king['kingdom_granaries'];
	$kingdom_woodsheds = $king['kingdom_woodsheds'];
	$kingdom_ironpits = $king['kingdom_ironpits'];
	$kingdom_vaults = $king['kingdom_vaults'];
	$kingdom_tower_lvl_bonus = 0;
	
	if($kingdom_towers_lvl > 1){
		$kingdom_tower_lvl_bonus = ($kingdom_towers_lvl * 500);
	}
	
	// Total Land
	$total_land = ($kingdom_farms + $kingdom_timber_mills + $kingdom_iron_mines + $kingdom_gold_mines + $kingdom_towers + $kingdom_granaries + $kingdom_woodsheds + $kingdom_ironpits + $kingdom_vaults + $kingdom_land);
	
	// Fetch Unit Data
	$units = fetch_all_unit_data();
	
	// Fetch Building Data
	$buildings = fetch_all_building_data();

	$total_net = floor(
	($units[1]['unit_net'] * $kingdom_villagers) +
	($units[2]['unit_net'] * $kingdom_soldiers) +
	($units[3]['unit_net'] * $kingdom_spies) +
	($units[4]['unit_net'] * $kingdom_macemen) +
	($units[5]['unit_net'] * $kingdom_axemen) +
	($units[6]['unit_net'] * $kingdom_spearmen) +
	($units[7]['unit_net'] * $kingdom_swordsmen) +
	($units[8]['unit_net'] * $kingdom_legionnaires) +
	($units[9]['unit_net'] * $kingdom_knights) +
	($units[10]['unit_net'] * $kingdom_slingers) +
	($units[11]['unit_net'] * $kingdom_bowmen) +
	($units[12]['unit_net'] * $kingdom_long_bowmen) +
	($units[13]['unit_net'] * $kingdom_crossbowmen) +
	($units[14]['unit_net'] * $kingdom_light_sword_cavalry) +
	($units[15]['unit_net'] * $kingdom_heavy_sword_cavalry) +
	($units[16]['unit_net'] * $kingdom_light_archer_cavalry) +
	($units[17]['unit_net'] * $kingdom_heavy_archer_cavalry) +
	($units[18]['unit_net'] * $kingdom_paladin) +
	($units[19]['unit_net'] * $kingdom_dragon_knights) +
	($units[20]['unit_net'] * $kingdom_rams) +
	($units[21]['unit_net'] * $kingdom_catapults) +
	($units[22]['unit_net'] * $kingdom_heavy_catapults) +
	($units[23]['unit_net'] * $kingdom_ballistas) +
	($units[24]['unit_net'] * $kingdom_trebuchets) +
	($units[25]['unit_net'] * $kingdom_chimeras) +
	($units[26]['unit_net'] * $kingdom_hydras) +
	($units[27]['unit_net'] * $kingdom_basilisks) +
	($units[28]['unit_net'] * $kingdom_wyverns) +
	($units[29]['unit_net'] * $kingdom_leviathans) +
	($units[30]['unit_net'] * $kingdom_dragons) +
	($buildings[1]['building_net'] * $kingdom_farms) +
	($buildings[2]['building_net'] * $kingdom_timber_mills) +
	($buildings[3]['building_net'] * $kingdom_iron_mines) +
	($buildings[4]['building_net'] * $kingdom_gold_mines) +
	($buildings[5]['building_net'] * $kingdom_towers) +
	($buildings[6]['building_net'] * $kingdom_granaries) +
	($buildings[7]['building_net'] * $kingdom_woodsheds) +
	($buildings[8]['building_net'] * $kingdom_ironpits) +
	($buildings[9]['building_net'] * $kingdom_vaults) +
	($kingdom_land * 50) +
	($kingdom_gold / 100000) +
	($kingdom_food / 10000) +
	($kingdom_wood / 1000) +
	($kingdom_iron / 100));

	$total_off = floor(
	($units[1]['unit_off'] * $kingdom_villagers) +
	($units[2]['unit_off'] * $kingdom_soldiers) +
	($units[3]['unit_off'] * $kingdom_spies) +
	($units[4]['unit_off'] * $kingdom_macemen) +
	($units[5]['unit_off'] * $kingdom_axemen) +
	($units[6]['unit_off'] * $kingdom_spearmen) +
	($units[7]['unit_off'] * $kingdom_swordsmen) +
	($units[8]['unit_off'] * $kingdom_legionnaires) +
	($units[9]['unit_off'] * $kingdom_knights) +
	($units[10]['unit_off'] * $kingdom_slingers) +
	($units[11]['unit_off'] * $kingdom_bowmen) +
	($units[12]['unit_off'] * $kingdom_long_bowmen) +
	($units[13]['unit_off'] * $kingdom_crossbowmen) +
	($units[14]['unit_off'] * $kingdom_light_sword_cavalry) +
	($units[15]['unit_off'] * $kingdom_heavy_sword_cavalry) +
	($units[16]['unit_off'] * $kingdom_light_archer_cavalry) +
	($units[17]['unit_off'] * $kingdom_heavy_archer_cavalry) +
	($units[18]['unit_off'] * $kingdom_paladin) +
	($units[19]['unit_off'] * $kingdom_dragon_knights) +
	($units[20]['unit_off'] * $kingdom_rams) +
	($units[21]['unit_off'] * $kingdom_catapults) +
	($units[22]['unit_off'] * $kingdom_heavy_catapults) +
	($units[23]['unit_off'] * $kingdom_ballistas) +
	($units[24]['unit_off'] * $kingdom_trebuchets) +
	($units[25]['unit_off'] * $kingdom_chimeras) +
	($units[26]['unit_off'] * $kingdom_hydras) +
	($units[27]['unit_off'] * $kingdom_basilisks) +
	($units[28]['unit_off'] * $kingdom_wyverns) +
	($units[29]['unit_off'] * $kingdom_leviathans) +
	($units[30]['unit_off'] * $kingdom_dragons ));
	
	$total_off = floor($total_off + ($total_off * $kingdom_off_bonus));

	$total_def = floor(
	($units[1]['unit_def'] * $kingdom_villagers) +
	($units[2]['unit_def'] * $kingdom_soldiers) +
	($units[3]['unit_def'] * $kingdom_spies) +
	($units[4]['unit_def'] * $kingdom_macemen) +
	($units[5]['unit_def'] * $kingdom_axemen) +
	($units[6]['unit_def'] * $kingdom_spearmen) +
	($units[7]['unit_def'] * $kingdom_swordsmen) +
	($units[8]['unit_def'] * $kingdom_legionnaires) +
	($units[9]['unit_def'] * $kingdom_knights) +
	($units[10]['unit_def'] * $kingdom_slingers) +
	($units[11]['unit_def'] * $kingdom_bowmen) +
	($units[12]['unit_def'] * $kingdom_long_bowmen) +
	($units[13]['unit_def'] * $kingdom_crossbowmen) +
	($units[14]['unit_def'] * $kingdom_light_sword_cavalry) +
	($units[15]['unit_def'] * $kingdom_heavy_sword_cavalry) +
	($units[16]['unit_def'] * $kingdom_light_archer_cavalry) +
	($units[17]['unit_def'] * $kingdom_heavy_archer_cavalry) +
	($units[18]['unit_def'] * $kingdom_paladin) +
	($units[19]['unit_def'] * $kingdom_dragon_knights) +
	($units[20]['unit_def'] * $kingdom_rams) +
	($units[21]['unit_def'] * $kingdom_catapults) +
	($units[22]['unit_def'] * $kingdom_heavy_catapults) +
	($units[23]['unit_def'] * $kingdom_ballistas) +
	($units[24]['unit_def'] * $kingdom_trebuchets) +
	($units[25]['unit_def'] * $kingdom_chimeras) +
	($units[26]['unit_def'] * $kingdom_hydras) +
	($units[27]['unit_def'] * $kingdom_basilisks) +
	($units[28]['unit_def'] * $kingdom_wyverns) +
	($units[29]['unit_def'] * $kingdom_leviathans) +
	($units[30]['unit_def'] * $kingdom_dragons ) +
	($buildings[1]['building_def'] * $kingdom_farms) +
	($buildings[2]['building_def'] * $kingdom_timber_mills ) +
	($buildings[3]['building_def'] * $kingdom_iron_mines) +
	($buildings[4]['building_def'] * $kingdom_gold_mines) +
	(($buildings[5]['building_def'] + $kingdom_tower_lvl_bonus) * $kingdom_towers) +
	($buildings[6]['building_def'] * $kingdom_granaries) +
	($buildings[7]['building_def'] * $kingdom_woodsheds) +
	($buildings[8]['building_def'] * $kingdom_ironpits) +
	($buildings[9]['building_def'] * $kingdom_vaults));
	
	$total_def = floor($total_def + ($total_def * $kingdom_def_bonus));

	$total_pop = (
	$kingdom_villagers +
	$kingdom_spies +
	$kingdom_soldiers +
	$kingdom_macemen +
	$kingdom_axemen +
	$kingdom_spearmen +
	$kingdom_swordsmen +
	$kingdom_legionnaires +
	$kingdom_knights +
	$kingdom_slingers +
	$kingdom_bowmen +
	$kingdom_long_bowmen +
	$kingdom_crossbowmen +
	$kingdom_light_sword_cavalry +
	$kingdom_heavy_sword_cavalry +
	$kingdom_light_archer_cavalry +
	$kingdom_heavy_archer_cavalry +
	$kingdom_paladin +
	$kingdom_dragon_knights +
	$kingdom_rams +
	$kingdom_catapults +
	$kingdom_heavy_catapults +
	$kingdom_ballistas +
	$kingdom_trebuchets +
	$kingdom_chimeras +
	$kingdom_hydras +
	$kingdom_basilisks +
	$kingdom_wyverns +
	$kingdom_leviathans +
	$kingdom_dragons);
			
	if($total_net < 0)
	{
		$total_net = 0;	
	}

	$db->sql_query(
	"UPDATE " . AOD_KINGDOMS_TABLE ." SET 
	kingdom_net = $total_net,
	kingdom_off = $total_off,
	kingdom_def = $total_def,
	kingdom_pop = $total_pop,
	kingdom_total_land = $total_land
	WHERE user_id = $user_id");
	$db->sql_return_on_error(false);
}

function report_kingdom_news($user_id,$report,$date)
{
	global $db,$user;
	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());
	}
	
	if(!$report)
	{
		trigger_error($user->lang['MISSING_REPORT'].back_link());
	}	
	
	$sql = 'INSERT INTO ' . AOD_KINGDOM_NEWS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'	=> $user_id,
		'report' 	=> $report,
		'date' 	=> $date,
		)
	);		  
	$db->sql_query($sql);
}

function report_transaction($user_id,$report,$link = NULL,$date)
{
	global $db,$user;
	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());
	}
	
	if(!$report)
	{
		trigger_error($user->lang['MISSING_REPORT'].back_link());
	}	
	
	$sql = 'INSERT INTO ' . AOD_REPORTS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'	=> $user_id,
		'report' 	=> $report,
		'link' 	=> $link,
		'date' 	=> $date,
		)
	);		  
	$db->sql_query($sql);
	
	// Update Kingdom Stats
	set_kingdom_stats($user_id);
}
 
function count_quests()
{
	global $db;
	$total = 0;

	$sql = 'SELECT count(*) as total 
	FROM ' . AOD_QUESTS_TABLE . '';
	$result = $db->sql_query($sql);
	while ($row = $db->sql_fetchrow($result))
	{
		$total = $row['total'];
	}
	
	return $total;
}

function fetch_quest_data($qid){
	global $db,$user;
	
	if(!$qid)
	{
		trigger_error($user->lang['MISSING_QUEST_ID'].back_link());	
		
	}else{
		$sql = "SELECT * 
		FROM " . AOD_QUESTS_TABLE . "
		WHERE id = $qid";
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$questdata = array(
			'id'								=> $row['id'],
			'quest_name'						=> $row['quest_name'],
			'quest_descript'					=> $row['quest_descript'],
			'quest_img_path'					=> $row['quest_img_path'],
			'quest_level_req'					=> $row['quest_level_req'],
			'quest_net_req'						=> $row['quest_net_req'],
			'quest_villagers_req'				=> $row['quest_villagers_req'],
			'quest_spies_req'					=> $row['quest_spies_req'],
			'quest_soldiers_req' 				=> $row['quest_soldiers_req'],
			'quest_macemen_req' 				=> $row['quest_macemen_req'],
			'quest_axemen_req'					=> $row['quest_axemen_req'],
			'quest_spearmen_req' 				=> $row['quest_spearmen_req'],
			'quest_swordsmen_req' 				=> $row['quest_swordsmen_req'],
			'quest_legionnaires_req' 			=> $row['quest_legionnaires_req'],
			'quest_knights_req' 				=> $row['quest_knights_req'],
			'quest_slingers_req' 				=> $row['quest_slingers_req'],
			'quest_bowmen_req'					=> $row['quest_bowmen_req'],
			'quest_long_bowmen_req' 			=> $row['quest_long_bowmen_req'],
			'quest_crossbowmen_req' 			=> $row['quest_crossbowmen_req'],
			'quest_light_sword_cavalry_req' 	=> $row['quest_light_sword_cavalry_req'],
			'quest_heavy_sword_cavalry_req' 	=> $row['quest_heavy_sword_cavalry_req'],
			'quest_light_archer_cavalry_req' 	=> $row['quest_light_archer_cavalry_req'],
			'quest_heavy_archer_cavalry_req' 	=> $row['quest_heavy_archer_cavalry_req'],
			'quest_paladin_req' 				=> $row['quest_paladin_req'],
			'quest_dragon_knights_req' 			=> $row['quest_dragon_knights_req'],
			'quest_rams_req'					=> $row['quest_rams_req'],
			'quest_catapults_req' 				=> $row['quest_catapults_req'],
			'quest_heavy_catapults_req' 		=> $row['quest_heavy_catapults_req'],
			'quest_ballistas_req' 				=> $row['quest_ballistas_req'],
			'quest_trebuchets_req' 				=> $row['quest_trebuchets_req'],
			'quest_chimeras_req' 				=> $row['quest_chimeras_req'],
			'quest_hydras_req'					=> $row['quest_hydras_req'],
			'quest_basilisks_req' 				=> $row['quest_basilisks_req'],
			'quest_wyverns_req' 				=> $row['quest_wyverns_req'],
			'quest_leviathans_req' 				=> $row['quest_leviathans_req'],
			'quest_dragons_req' 				=> $row['quest_dragons_req'],
			'quest_farms_req'					=> $row['quest_farms_req'],
			'quest_timber_mills_req' 			=> $row['quest_timber_mills_req'],
			'quest_iron_mines_req' 				=> $row['quest_iron_mines_req'],
			'quest_gold_mines_req' 				=> $row['quest_gold_mines_req'],
			'quest_towers_req'					=> $row['quest_towers_req'],
			'quest_granaries_req' 				=> $row['quest_granaries_req'],
			'quest_woodsheds_req' 				=> $row['quest_woodsheds_req'],
			'quest_ironpits_req' 				=> $row['quest_ironpits_req'],
			'quest_vaults_req'					=> $row['quest_vaults_req'],
			'quest_land_req'					=> $row['quest_land_req'],
			'quest_stamina_req'					=> $row['quest_stamina_req'],
			'quest_gold_req'					=> $row['quest_gold_req'],
			'quest_food_req'					=> $row['quest_food_req'],
			'quest_wood_req'					=> $row['quest_wood_req'],
			'quest_iron_req'					=> $row['quest_iron_req'],
			'quest_min_villagers'				=> $row['quest_min_villagers'], 
			'quest_max_villagers'				=> $row['quest_max_villagers'],
			'quest_min_gold'					=> $row['quest_min_gold'], 
			'quest_max_gold'					=> $row['quest_max_gold'], 
			'quest_min_food'					=> $row['quest_min_food'], 
			'quest_max_food'					=> $row['quest_max_food'], 
			'quest_min_wood'					=> $row['quest_min_wood'],
			'quest_max_wood'					=> $row['quest_max_wood'], 
			'quest_min_iron'					=> $row['quest_min_iron'], 
			'quest_max_iron'					=> $row['quest_max_iron'], 
			'quest_min_dragoncoins'				=> $row['quest_min_dragoncoins'], 
			'quest_max_dragoncoins'				=> $row['quest_max_dragoncoins'], 
			'quest_min_exp'						=> $row['quest_min_exp'], 
			'quest_max_exp'						=> $row['quest_max_exp'],
			'quest_min_soldiers' 				=> $row['quest_min_soldiers'],
			'quest_max_soldiers' 				=> $row['quest_max_soldiers'],
			'quest_min_spies' 					=> $row['quest_min_spies'],
			'quest_max_spies' 					=> $row['quest_max_spies'],
			'quest_min_macemen' 				=> $row['quest_min_macemen'],
			'quest_max_macemen' 				=> $row['quest_max_macemen'],
			'quest_min_axemen' 					=> $row['quest_min_axemen'],
			'quest_max_axemen' 					=> $row['quest_max_axemen'],
			'quest_min_spearmen' 				=> $row['quest_min_spearmen'],
			'quest_max_spearmen' 				=> $row['quest_max_spearmen'],
			'quest_min_swordsmen' 				=> $row['quest_min_swordsmen'],
			'quest_max_swordsmen' 				=> $row['quest_max_swordsmen'],
			'quest_min_legionnaires' 			=> $row['quest_min_legionnaires'],
			'quest_max_legionnaires' 			=> $row['quest_max_legionnaires'],
			'quest_min_knights' 				=> $row['quest_min_knights'],
			'quest_max_knights' 				=> $row['quest_max_knights'],
			'quest_min_slingers' 				=> $row['quest_min_slingers'],
			'quest_max_slingers' 				=> $row['quest_max_slingers'],
			'quest_min_bowmen' 					=> $row['quest_min_bowmen'],
			'quest_max_bowmen' 					=> $row['quest_max_bowmen'],
			'quest_min_long_bowmen' 			=> $row['quest_min_long_bowmen'],
			'quest_max_long_bowmen' 			=> $row['quest_max_long_bowmen'],
			'quest_min_crossbowmen' 			=> $row['quest_min_crossbowmen'],
			'quest_max_crossbowmen' 			=> $row['quest_max_crossbowmen'],
			'quest_min_light_sword_cavalry' 	=> $row['quest_min_light_sword_cavalry'],
			'quest_max_light_sword_cavalry' 	=> $row['quest_max_light_sword_cavalry'],
			'quest_min_heavy_sword_cavalry' 	=> $row['quest_min_heavy_sword_cavalry'],
			'quest_max_heavy_sword_cavalry' 	=> $row['quest_max_heavy_sword_cavalry'],
			'quest_min_light_archer_cavalry' 	=> $row['quest_min_light_archer_cavalry'],
			'quest_max_light_archer_cavalry' 	=> $row['quest_max_light_archer_cavalry'],
			'quest_min_heavy_archer_cavalry' 	=> $row['quest_min_heavy_archer_cavalry'],
			'quest_max_heavy_archer_cavalry' 	=> $row['quest_max_heavy_archer_cavalry'],
			'quest_min_paladin' 				=> $row['quest_min_paladin'],
			'quest_max_paladin' 				=> $row['quest_max_paladin'],
			'quest_min_dragon_knights' 			=> $row['quest_min_dragon_knights'],
			'quest_max_dragon_knights' 			=> $row['quest_max_dragon_knights'],
			'quest_min_rams' 					=> $row['quest_min_rams'],
			'quest_max_rams' 					=> $row['quest_max_rams'],
			'quest_min_catapults' 				=> $row['quest_min_catapults'],
			'quest_max_catapults' 				=> $row['quest_max_catapults'],
			'quest_min_heavy_catapults' 		=> $row['quest_min_heavy_catapults'],
			'quest_max_heavy_catapults' 		=> $row['quest_max_heavy_catapults'],
			'quest_min_ballistas' 				=> $row['quest_min_ballistas'],
			'quest_max_ballistas' 				=> $row['quest_max_ballistas'],
			'quest_min_trebuchets' 				=> $row['quest_min_trebuchets'],
			'quest_max_trebuchets' 				=> $row['quest_max_trebuchets'],
			'quest_min_chimeras' 				=> $row['quest_min_chimeras'],
			'quest_max_chimeras' 				=> $row['quest_max_chimeras'],
			'quest_min_hydras' 					=> $row['quest_min_hydras'],
			'quest_max_hydras' 					=> $row['quest_max_hydras'],
			'quest_min_basilisks' 				=> $row['quest_min_basilisks'],
			'quest_max_basilisks' 				=> $row['quest_max_basilisks'],
			'quest_min_wyverns' 				=> $row['quest_min_wyverns'],
			'quest_max_wyverns' 				=> $row['quest_max_wyverns'],
			'quest_min_leviathans' 				=> $row['quest_min_leviathans'],
			'quest_max_leviathans' 				=> $row['quest_max_leviathans'],
			'quest_min_dragons' 				=> $row['quest_min_dragons'],
			'quest_max_dragons' 				=> $row['quest_max_dragons'],
			'quest_min_land' 					=> $row['quest_min_land'],
			'quest_max_land' 					=> $row['quest_max_land'],
			'quest_min_farms' 					=> $row['quest_min_farms'],
			'quest_max_farms' 					=> $row['quest_max_farms'],
			'quest_min_timber_mills' 			=> $row['quest_min_timber_mills'],
			'quest_max_timber_mills'		 	=> $row['quest_max_timber_mills'],
			'quest_min_iron_mines' 				=> $row['quest_min_iron_mines'],
			'quest_max_iron_mines' 				=> $row['quest_max_iron_mines'],
			'quest_min_gold_mines' 				=> $row['quest_min_gold_mines'],
			'quest_max_gold_mines' 				=> $row['quest_max_gold_mines'],
			'quest_min_towers' 					=> $row['quest_min_towers'],
			'quest_max_towers' 					=> $row['quest_max_towers'],
			'quest_min_granaries' 				=> $row['quest_min_granaries'],
			'quest_max_granaries' 				=> $row['quest_max_granaries'],
			'quest_min_woodsheds' 				=> $row['quest_min_woodsheds'],
			'quest_max_woodsheds' 				=> $row['quest_max_woodsheds'],
			'quest_min_ironpits' 				=> $row['quest_min_ironpits'],  
			'quest_max_ironpits' 				=> $row['quest_max_ironpits'],
			'quest_min_vaults' 					=> $row['quest_min_vaults'],
			'quest_max_vaults' 					=> $row['quest_max_vaults'],			
			'quest_chance'						=> $row['quest_chance'],
			'quest_approved'					=> $row['quest_approved'],
			);  		
		}	
		$db->sql_freeresult($result);
		
		return $questdata;
	}
}

function fetch_building_data($bid)
{
	global $db,$user;

	if(!$bid)
	{
		trigger_error($user->lang['MISSING_BUILDING_ID'].back_link());	
	}else{
		
		$sql = "SELECT * 
		FROM " . AOD_BUILDINGS_TABLE . "
		WHERE id = $bid";
		$result = $db->sql_query($sql);
	
		if($row = $db->sql_fetchrow($result))
		{
			$building_data = array(
				'id' 					=> $row['id'],
				'building_name'			=> $row['building_name'],
				'building_net'			=> $row['building_net'],
				'building_def'			=> $row['building_def'],
				'building_gold'			=> $row['building_gold'],
				'building_wood'			=> $row['building_wood'],
				'building_iron'			=> $row['building_iron'],
			);  		
		}	
		$db->sql_freeresult($result);
	
		return $building_data;	
	}
}

function fetch_all_building_data()
{
	global $db;
		
	$sql = "SELECT * 
	FROM " . AOD_BUILDINGS_TABLE . "
	ORDER BY id ASC";
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$bid = $row['id'];
		$building_data [$bid] = array(
			'id' 					=> $row['id'],
			'building_name'			=> $row['building_name'],
			'building_net'			=> $row['building_net'],
			'building_def'			=> $row['building_def'],
			'building_gold'			=> $row['building_gold'],
			'building_wood'			=> $row['building_wood'],
			'building_iron'			=> $row['building_iron'],
		);  		
	}	
	$db->sql_freeresult($result);

	return $building_data;	
}

function fetch_unit_data($uid)
{
	global $db,$user;
	
	if(!$uid)
	{
		trigger_error($user->lang['MISSING_UNIT_ID'].back_link());	
	}else{
				
		$sql = "SELECT * 
		FROM " . AOD_UNITS_TABLE . "
		WHERE id = $uid";
		$result = $db->sql_query($sql);
	
		if($row = $db->sql_fetchrow($result))
		{

			$unit_data = array(
				'id' 				=> $row['id'],
				'unit_name'			=> $row['unit_name'],
				'unit_net'			=> $row['unit_net'],
				'unit_off'			=> $row['unit_off'],
				'unit_def'			=> $row['unit_def'],
				'unit_gold'			=> $row['unit_gold'],
				'unit_food'			=> $row['unit_food'],
				'unit_wood'			=> $row['unit_wood'],
				'unit_wood'			=> $row['unit_wood'],
				'unit_iron'			=> $row['unit_iron'],
				'unit_level'		=> $row['unit_level'],
			);  		
		}	
		$db->sql_freeresult($result);
	
		return $unit_data;
	}
}

function fetch_all_unit_data()
{
	global $db;
		
	$sql = "SELECT * 
	FROM " . AOD_UNITS_TABLE . "
	ORDER BY id ASC";
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$uid = $row['id'];
		$unit_data [$uid] = array(
			'id' 				=> $row['id'],
			'unit_name'			=> $row['unit_name'],
			'unit_net'			=> $row['unit_net'],
			'unit_off'			=> $row['unit_off'],
			'unit_def'			=> $row['unit_def'],
			'unit_gold'			=> $row['unit_gold'],
			'unit_food'			=> $row['unit_food'],
			'unit_wood'			=> $row['unit_wood'],
			'unit_wood'			=> $row['unit_wood'],
			'unit_iron'			=> $row['unit_iron'],
			'unit_level'		=> $row['unit_level'],
		);  		
	}	
	$db->sql_freeresult($result);

	return $unit_data;	
}

function fetch_kingdom_data($user_id)
{
	global $db,$user;

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());	
	}else{
		
		$sql = "SELECT * 
		FROM " . AOD_KINGDOMS_TABLE . "
		WHERE user_id = $user_id";
		$result = $db->sql_query($sql);
	
		if($row = $db->sql_fetchrow($result))
		{
		
			$kingdom_data = array(
				'id' 									=> $row['id'],
				'admin_access'							=> $row['admin_access'],
				'user_id' 								=> $row['user_id'],
				'kingdom_status' 						=> $row['kingdom_status'],
				'kingdom_name' 							=> $row['kingdom_name'],
				'kingdom_ruler' 						=> $row['kingdom_ruler'],
				'kingdom_advantage' 					=> $row['kingdom_advantage'],
				'kingdom_level' 						=> $row['kingdom_level'],
				'kingdom_wins' 							=> $row['kingdom_wins'],
				'kingdom_losses' 						=> $row['kingdom_losses'],
				'kingdom_exp' 							=> $row['kingdom_exp'],
				'kingdom_pop' 							=> $row['kingdom_pop'],
				'kingdom_net' 							=> $row['kingdom_net'],
				'kingdom_off' 							=> $row['kingdom_off'],
				'kingdom_off_bonus' 					=> $row['kingdom_off_bonus'],
				'kingdom_def' 							=> $row['kingdom_def'],
				'kingdom_def_bonus' 					=> $row['kingdom_def_bonus'],
				'kingdom_unit_bonus' 					=> $row['kingdom_unit_bonus'],
				'kingdom_food' 							=> $row['kingdom_food'],
				'kingdom_wood' 							=> $row['kingdom_wood'],
				'kingdom_iron' 							=> $row['kingdom_iron'],
				'kingdom_gold' 							=> $row['kingdom_gold'],
				'kingdom_land' 							=> $row['kingdom_land'],
				'kingdom_total_land'					=> $row['kingdom_total_land'],
				'kingdom_turns' 						=> $row['kingdom_turns'],
				'kingdom_turns_max' 					=> $row['kingdom_turns_max'],
				'kingdom_turns_income' 					=> $row['kingdom_turns_income'],
				'kingdom_stamina' 						=> $row['kingdom_stamina'],
				'kingdom_stamina_max' 					=> $row['kingdom_stamina_max'],
				'kingdom_stamina_income' 				=> $row['kingdom_stamina_income'],
				'kingdom_villagers' 					=> $row['kingdom_villagers'],
				'kingdom_villagers_income' 				=> $row['kingdom_villagers_income'],
				'kingdom_spies' 						=> $row['kingdom_spies'],
				'kingdom_soldiers' 						=> $row['kingdom_soldiers'],
				'kingdom_macemen' 						=> $row['kingdom_macemen'],
				'kingdom_axemen'		 				=> $row['kingdom_axemen'],
				'kingdom_spearmen' 						=> $row['kingdom_spearmen'],
				'kingdom_swordsmen' 					=> $row['kingdom_swordsmen'],
				'kingdom_legionnaires' 					=> $row['kingdom_legionnaires'],
				'kingdom_knights' 						=> $row['kingdom_knights'],
				'kingdom_slingers' 						=> $row['kingdom_slingers'],
				'kingdom_bowmen' 						=> $row['kingdom_bowmen'],
				'kingdom_long_bowmen' 					=> $row['kingdom_long_bowmen'],
				'kingdom_crossbowmen' 					=> $row['kingdom_crossbowmen'],
				'kingdom_light_sword_cavalry' 			=> $row['kingdom_light_sword_cavalry'],
				'kingdom_heavy_sword_cavalry' 			=> $row['kingdom_heavy_sword_cavalry'],
				'kingdom_light_archer_cavalry' 			=> $row['kingdom_light_archer_cavalry'],
				'kingdom_heavy_archer_cavalry' 			=> $row['kingdom_heavy_archer_cavalry'],
				'kingdom_paladin' 						=> $row['kingdom_paladin'],
				'kingdom_dragon_knights' 				=> $row['kingdom_dragon_knights'],
				'kingdom_rams' 							=> $row['kingdom_rams'],
				'kingdom_catapults' 					=> $row['kingdom_catapults'],
				'kingdom_heavy_catapults' 				=> $row['kingdom_heavy_catapults'],
				'kingdom_ballistas' 					=> $row['kingdom_ballistas'],
				'kingdom_trebuchets' 					=> $row['kingdom_trebuchets'],
				'kingdom_chimeras' 						=> $row['kingdom_chimeras'],
				'kingdom_hydras' 						=> $row['kingdom_hydras'],
				'kingdom_basilisks' 					=> $row['kingdom_basilisks'],
				'kingdom_wyverns' 						=> $row['kingdom_wyverns'],
				'kingdom_leviathans' 					=> $row['kingdom_leviathans'],
				'kingdom_dragons' 						=> $row['kingdom_dragons'],

				'kingdom_farms_lvl' 					=> $row['kingdom_farms_lvl'],
				'kingdom_farms' 						=> $row['kingdom_farms'],
				'kingdom_farms_income' 					=> $row['kingdom_farms_income'],

				'kingdom_timber_mills_lvl' 				=> $row['kingdom_timber_mills_lvl'],
				'kingdom_timber_mills' 					=> $row['kingdom_timber_mills'],
				'kingdom_timber_mills_income' 			=> $row['kingdom_timber_mills_income'],

				'kingdom_iron_mines_lvl' 				=> $row['kingdom_iron_mines_lvl'],
				'kingdom_iron_mines' 					=> $row['kingdom_iron_mines'],
				'kingdom_iron_mines_income' 			=> $row['kingdom_iron_mines_income'],

				'kingdom_gold_mines_lvl' 				=> $row['kingdom_gold_mines_lvl'],
				'kingdom_gold_mines' 					=> $row['kingdom_gold_mines'],
				'kingdom_gold_mines_income' 			=> $row['kingdom_gold_mines_income'],
				
				'kingdom_towers_lvl' 					=> $row['kingdom_towers_lvl'],
				'kingdom_towers' 						=> $row['kingdom_towers'],
				
				'kingdom_granaries_lvl'		 			=> $row['kingdom_granaries_lvl'],
				'kingdom_granaries' 					=> $row['kingdom_granaries'],
				'kingdom_granaries_max' 				=> $row['kingdom_granaries_max'],
				
				'kingdom_woodsheds_lvl'		 			=> $row['kingdom_woodsheds_lvl'],
				'kingdom_woodsheds' 					=> $row['kingdom_woodsheds'],
				'kingdom_woodsheds_max' 				=> $row['kingdom_woodsheds_max'],
				
				'kingdom_ironpits_lvl' 					=> $row['kingdom_ironpits_lvl'],
				'kingdom_ironpits' 						=> $row['kingdom_ironpits'],
				'kingdom_ironpits_max' 					=> $row['kingdom_ironpits_max'],
				
				'kingdom_vaults_lvl' 					=> $row['kingdom_vaults_lvl'],
				'kingdom_vaults' 						=> $row['kingdom_vaults'],
				'kingdom_vaults_max' 					=> $row['kingdom_vaults_max'],
				
				'kingdom_sponsor' 						=> $row['kingdom_sponsor'],
				'kingdom_coins' 						=> $row['kingdom_coins'],
			);  		
		}	
		$db->sql_freeresult($result);
	
		return $kingdom_data;	
	}
}

function delete_account($game_id,$user_id)
{
	global $db, $user, $phpbb_root_path, $phpEx;
	
	if(!$game_id)
	{
		trigger_error($user->lang['MISSING_GAME_ID'].back_link());
	}

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());
	}	

	$gc_account_status = gc_check_account_status($user_id,$game_id);
	$aod_account_status = check_account_status($user_id);

	if($gc_account_status == TRUE AND $aod_account_status == TRUE)
	{
		// Remove the main game listing table
		$db->sql_query('DELETE FROM ' . AOD_KINGDOMS_TABLE . " WHERE user_id = $user_id");
	
		// Remove the data from the accounts table
		$db->sql_query('DELETE FROM ' . GC_ACCOUNTS_TABLE . " WHERE game_id = $game_id AND user_id = $user_id");

		// Subtract 1 from the games member count 
		remove_member();
	}
}

function create_account($game_id,$user_id,$kingdom_ruler,$kingdom_name,$kingdom_advantage)
{
	global $db, $user, $phpbb_root_path, $phpEx,$aod_config;

	$kingdom_ruler = clean_text($kingdom_ruler,1);
	$kingdom_name = clean_text($kingdom_name,1);

	if(!$game_id)
	{
		trigger_error($user->lang['MISSING_GAME_ID'].back_link());
	}

	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());
	}	

	if(!$kingdom_ruler)
	{
		trigger_error($user->lang['MISSING_KINGDOM_RULER'].back_link());
	}	

	if(!$kingdom_name)
	{
		trigger_error($user->lang['MISSING_KINGDOM_NAME'].back_link());
	}	

	if(!$kingdom_advantage)
	{
		trigger_error($user->lang['MISSING_KINGDOM_ADVANTAGE'].back_link());
	}	
	
	$kingdom_ruler_length_check = strlen($kingdom_ruler);
	
	if($kingdom_ruler_length_check < 5)
	{
		trigger_error($user->lang['KINGDOM_RULER_TO_SHORT'].back_link());
	}	
	
	$kingdom_name_length_check = strlen($kingdom_name);
	
	if($kingdom_name_length_check < 5)
	{
		trigger_error($user->lang['KINGDOM_NAME_TO_SHORT'].back_link());
	}	
	
	validate_kingdom_ruler($kingdom_ruler , 'USERNAME_LETTER_NUM_SPACERS');
	validate_kingdom_name($kingdom_name , 'USERNAME_LETTER_NUM_SPACERS');

	$account_status = gc_check_account_status($user->data['user_id'],$game_id);
	
	if($account_status)
	{
		redirect(append_sid("{$phpbb_root_path}games/index.$phpEx"));
	}
		
	Switch($kingdom_advantage)
	{
		case 1:// More Turns
			$kingdom_turns_max = ($aod_config['turns_advantage'] + 10);
			$kingdom_turns = ($aod_config['turns_advantage'] + 10);
			$kingdom_stamina_max = 10;
			$kingdom_stamina = 10;
			$kingdom_off_bonus = 0;
			$kingdom_def_bonus = 0;
			$kingdom_unit_bonus = 0;
			
		break;
		
		case 2:// More Stamina
			$kingdom_turns_max = 10;
			$kingdom_turns = 10;
			$kingdom_stamina_max = ($aod_config['stamina_advantage'] + 10);
			$kingdom_stamina = ($aod_config['stamina_advantage'] + 10);
			$kingdom_off_bonus = 0;
			$kingdom_def_bonus = 0;
			$kingdom_unit_bonus = 0;
		
		break;
		
		case 3:// More Off & Def
			$kingdom_turns = 10;
			$kingdom_turns_max = 10;
			$kingdom_stamina = 10;
			$kingdom_stamina_max = 10;
			$kingdom_off_bonus = $aod_config['offdef_advantage'];
			$kingdom_def_bonus = $aod_config['offdef_advantage'];
			$kingdom_unit_bonus = 0;
			
		break;
		
		case 4:// Unit Cost Discount
			$kingdom_turns = 10;
			$kingdom_turns_max = 10;
			$kingdom_stamina = 10;
			$kingdom_stamina_max = 10;
			$kingdom_off_bonus = 0;
			$kingdom_def_bonus = 0;
			$kingdom_unit_bonus = $aod_config['unitcost_advantage'];
			
		break;
	}
	

	// This sets the max amount in which a single granary can hold
	$granaries_max = $aod_config['granaries_max'];

	// This sets the max amount in which a single woodshed can hold
	$woodsheds_max = $aod_config['woodsheds_max'];

	// This sets the max amount in which a single ironpit can hold
	$ironpits_max = $aod_config['ironpits_max'];

	// This sets the max amount in which a single vault can hold
	$vaults_max = $aod_config['vaults_max'];
	
	// This will randomly set the users farm income 
	$farms_income = rand($aod_config['farms_income_min'] , $aod_config['farms_income_max']);

	// This will randomly set the users timber mill income
	$timber_mills_income = rand($aod_config['timber_mills_income_min'] , $aod_config['timber_mills_income_max']);

	// This will randomly set the users iron mine income
	$iron_mines_income = rand($aod_config['iron_mines_income_min'] , $aod_config['iron_mines_income_max']);

	// This will randomly set the users gold mine income
	$gold_mines_income = rand($aod_config['gold_mines_income_min'] , $aod_config['gold_mines_income_max']);
	
	// This sets the amount of farms the user will start with
	$start_farms = $aod_config['start_farms'];

	// This sets the amount of timber mills the user will start with
	$start_timbermills = $aod_config['start_timbermills'];

	// This sets the amount of iron mines the user will start with
	$start_ironmines = $aod_config['start_ironmines'];

	// This sets the amount of gold mines the user will start with
	$start_goldmines = $aod_config['start_goldmines'];

	// This sets the amount of granaries the user will start with
	$start_granaries = $aod_config['start_granaries'];

	// This sets the amount of woodsheds the user will start with
	$start_woodsheds = $aod_config['start_woodsheds'];

	// This sets the amount of ironpits the user will start with
	$start_ironpits = $aod_config['start_ironpits'];

	// This sets the amount of vaults the user will start with
	$start_vaults = $aod_config['start_vaults'];
 
	$sql = 'INSERT INTO ' . AOD_KINGDOMS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
		'user_id' 						=> $user_id,
		'kingdom_ruler' 				=> $kingdom_ruler,
		'kingdom_name' 					=> $kingdom_name,
		'kingdom_advantage'				=> $kingdom_advantage,
		'kingdom_turns_max'				=> $kingdom_turns_max,
		'kingdom_turns'					=> $kingdom_turns,
		'kingdom_stamina_max'			=> $kingdom_stamina_max,
		'kingdom_stamina'				=> $kingdom_stamina,
		'kingdom_off_bonus'				=> $kingdom_off_bonus,
		'kingdom_def_bonus'				=> $kingdom_def_bonus,
		'kingdom_unit_bonus'			=> $kingdom_unit_bonus,
		'kingdom_granaries_max'			=> $granaries_max,
		'kingdom_woodsheds_max'			=> $woodsheds_max,
		'kingdom_ironpits_max'			=> $ironpits_max,
		'kingdom_vaults_max'			=> $vaults_max,
		'kingdom_farms_income'			=> $farms_income,
		'kingdom_timber_mills_income'	=> $timber_mills_income,
		'kingdom_iron_mines_income'		=> $iron_mines_income,
		'kingdom_gold_mines_income'		=> $gold_mines_income,
		'kingdom_farms'					=> $start_farms,
		'kingdom_timber_mills'			=> $start_timbermills,
		'kingdom_iron_mines'			=> $start_ironmines,
		'kingdom_gold_mines'			=> $start_goldmines,
		'kingdom_granaries'				=> $start_granaries,
		'kingdom_woodsheds'				=> $start_woodsheds,
		'kingdom_ironpits'				=> $start_ironpits,
		'kingdom_vaults'				=> $start_vaults,
		
		)
	);		  
	$db->sql_query($sql);

	// Add a record in to game console accounts
	$sql = 'INSERT INTO ' . GC_ACCOUNTS_TABLE .' ' . $db->sql_build_array('INSERT', array(
		'user_id' 	=> $user_id,
		'game_id' 	=> $game_id,
		)
	);		  
	$db->sql_query($sql);

	// Add 1 to the games member count 
	add_member();

	// Set Kingdom Stats
	set_kingdom_stats($user_id);

	trigger_error($user->lang['ACCOUNT_CREATION_SUCCESSFULL'].'<br /><br /><a href="index.php?gameid='.$game_id.'">'.$user->lang['CLICK_HERE_TO_BEGIN_PLAYING'].'</a>');	
}

function sync_member_count()
{
	global $db, $user, $cache;
	$gameid = gc_fetch_gid('aod');
	$gdata = gc_fetch_game_data($gameid);
	$accounts = count_kingdoms();
	
	if($gdata['members'] <> $accounts){
		$db->sql_query(
		"UPDATE " . GC_GAMES_TABLE ." SET 
		game_members = $accounts
		WHERE id = $gameid");
		$db->sql_return_on_error(false);
	}		
}

function remove_member()
{
	global $db, $user, $cache;
	$gameid = gc_fetch_gid('aod');
	
	$db->sql_query(
	"UPDATE " . GC_GAMES_TABLE ." SET 
	game_members = game_members - 1
	WHERE id = $gameid");
	$db->sql_return_on_error(false);
	
}

function add_member()
{
	global $db, $user, $cache;
	$gameid = gc_fetch_gid('aod');
	
	$db->sql_query(
	"UPDATE " . GC_GAMES_TABLE ." SET 
	game_members = game_members + 1
	WHERE id = $gameid");
	$db->sql_return_on_error(false);
}

function validate_kingdom_ruler($kingdom_ruler,$allowed_name_chars)
{
	global $db, $user, $cache;
	
	$clean_kingdom_ruler = utf8_clean_string($kingdom_ruler);
	
	
	// ... fast checks first.
	if (strpos($kingdom_ruler, '&quot;') !== false || strpos($kingdom_ruler, '"') !== false || empty($clean_kingdom_ruler))
	{
		trigger_error($user->lang['KINGDOM_RULER_INVALID_CHARS'].back_link());
	}

	$mbstring = $pcre = false;

	// generic UTF-8 character types supported?
	if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
	{
		$pcre = true;
	}
	else if (function_exists('mb_ereg_match'))
	{
		mb_regex_encoding('UTF-8');
		$mbstring = true;
	}

	switch ($allowed_name_chars)
	{
		case 'USERNAME_CHARS_ANY':
			$pcre = true;
			$regex = '.+';
		break;

		case 'USERNAME_ALPHA_ONLY':
			$pcre = true;
			$regex = '[A-Za-z0-9]+';
		break;

		case 'USERNAME_ALPHA_SPACERS':
			$pcre = true;
			$regex = '[A-Za-z0-9-[\]_+ ]+';
		break;

		case 'USERNAME_LETTER_NUM':
			if ($pcre)
			{
				$regex = '[\p{Lu}\p{Ll}\p{N}]+';
			}
			else if ($mbstring)
			{
				$regex = '[[:upper:][:lower:][:digit:]]+';
			}
			else
			{
				$pcre = true;
				$regex = '[a-zA-Z0-9]+';
			}
		break;

		case 'USERNAME_LETTER_NUM_SPACERS':
			if ($pcre)
			{
				$regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
			}
			else if ($mbstring)
			{
				$regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
			}
			else
			{
				$pcre = true;
				$regex = '[-\]_+ [a-zA-Z0-9]+';
			}
		break;

		case 'USERNAME_ASCII':
		default:
			$pcre = true;
			$regex = '[\x01-\x7F]+';
		break;
	}

	if ($pcre)
	{
		if (!preg_match('#^' . $regex . '$#u', $kingdom_ruler))
		{
			trigger_error($user->lang['KINGDOM_RULER_INVALID_CHARS'].back_link());
		}
	}
	else if ($mbstring)
	{
		mb_ereg_search_init($kingdom_ruler, '^' . $regex . '$');
		if (!mb_ereg_search())
		{
			trigger_error($user->lang['KINGDOM_RULER_INVALID_CHARS'].back_link());
		}
	}

	$sql = 'SELECT *
		FROM ' . AOD_KINGDOMS_TABLE . "
		WHERE LOWER(kingdom_ruler) = '" . $db->sql_escape($clean_kingdom_ruler) . "'";
	$result = $db->sql_query($sql);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	if ($row)
	{
		trigger_error($user->lang['KINGDOM_NAME_TAKEN'].back_link());
	}
	
	$bad_usernames = $cache->obtain_disallowed_usernames();

	foreach ($bad_usernames as $bad_username)
	{
		if (preg_match('#^' . $bad_username . '$#', $clean_kingdom_ruler))
		{
			trigger_error($user->lang['KINGDOM_RULER_DISALLOWED'].back_link());
		}
	}

	return false;	
}

function validate_kingdom_name($kingdom_name,$allowed_name_chars)
{
	global $db, $user, $cache;
	
	$clean_kingdom_name = utf8_clean_string($kingdom_name);
 
	// ... fast checks first.
	if (strpos($kingdom_name, '&quot;') !== false || strpos($kingdom_name, '"') !== false || empty($clean_kingdom_name))
	{
		trigger_error($user->lang['KINGDOM_NAME_INVALID_CHARS'].back_link());
	}

	$mbstring = $pcre = false;

	// generic UTF-8 character types supported?
	if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
	{
		$pcre = true;
	}
	else if (function_exists('mb_ereg_match'))
	{
		mb_regex_encoding('UTF-8');
		$mbstring = true;
	}

	switch ($allowed_name_chars)
	{
		case 'USERNAME_CHARS_ANY':
			$pcre = true;
			$regex = '.+';
		break;

		case 'USERNAME_ALPHA_ONLY':
			$pcre = true;
			$regex = '[A-Za-z0-9]+';
		break;

		case 'USERNAME_ALPHA_SPACERS':
			$pcre = true;
			$regex = '[A-Za-z0-9-[\]_+ ]+';
		break;

		case 'USERNAME_LETTER_NUM':
			if ($pcre)
			{
				$regex = '[\p{Lu}\p{Ll}\p{N}]+';
			}
			else if ($mbstring)
			{
				$regex = '[[:upper:][:lower:][:digit:]]+';
			}
			else
			{
				$pcre = true;
				$regex = '[a-zA-Z0-9]+';
			}
		break;

		case 'USERNAME_LETTER_NUM_SPACERS':
			if ($pcre)
			{
				$regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
			}
			else if ($mbstring)
			{
				$regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
			}
			else
			{
				$pcre = true;
				$regex = '[-\]_+ [a-zA-Z0-9]+';
			}
		break;

		case 'USERNAME_ASCII':
		default:
			$pcre = true;
			$regex = '[\x01-\x7F]+';
		break;
	}

	if ($pcre)
	{
		if (!preg_match('#^' . $regex . '$#u', $kingdom_name))
		{
			trigger_error($user->lang['KINGDOM_NAME_INVALID_CHARS'].back_link());
		}
	}
	else if ($mbstring)
	{
		mb_ereg_search_init($kingdom_name, '^' . $regex . '$');
		if (!mb_ereg_search())
		{
			trigger_error($user->lang['KINGDOM_NAME_INVALID_CHARS'].back_link());
		}
	}
	
	$sql = 'SELECT *
		FROM ' . AOD_KINGDOMS_TABLE . "
		WHERE LOWER(kingdom_name) = '" . $db->sql_escape($clean_kingdom_name) . "'";
	$result = $db->sql_query($sql);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	if ($row)
	{
		trigger_error($user->lang['KINGDOM_NAME_TAKEN'].back_link());
	}
	
	$bad_usernames = $cache->obtain_disallowed_usernames();

	foreach ($bad_usernames as $bad_username)
	{
		if (preg_match('#^' . $bad_username . '$#', $clean_kingdom_name))
		{
			trigger_error($user->lang['KINGDOM_NAME_DISALLOWED'].back_link());
		}
	}
	
	return false;	
}

function check_account_status($user_id)
{
	global $db,$user;
	$account_status = 0;
	
	if(!$user_id)
	{
		trigger_error($user->lang['MISSING_USER_ID'].back_link());	

	}else{
		
		$sql = 'SELECT *
		FROM ' . AOD_KINGDOMS_TABLE . '
		WHERE user_id = '.$user_id;
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		if($row)
		{
			$account_status = TRUE;
		}
	
		return $account_status;
	}
}

function clean_text($text,$mode)
{

	$code_entities_match = array('&amp;','&nbsp;','',' ','@','#','$','%','^','&','*','(',')','_','+','-','=','!','`','~','[',']','{','}',':',';','|','\\','<','>',',','.','?','/','"',"'",'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
	
	switch($mode)
	{
		default: // Some special characters are allowed
			$code_entities_replace = array('','','',' ','@','#','$','%','^', '','*','(',')','_','+','-','=','!','`','~','[',']','{','}',':', '','|','\\', '', '',',','.','?','/','"',"'",'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		break;

		case 1: // No Special characters are allowed
			$code_entities_replace = array('','','',' ','','','','','', '','','','','_','','-','','','','','','','','','', '','','', '', '','','','','','',"",'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		break;

		case 2: // Numbers only
			$code_entities_replace = array('','','','','','','','','', '','','','','','','','','','','','','','','','', '','','', '', '','','','','','',"",'0','1','2','3','4','5','6','7','8','9','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
		break;
				
		case 3: // Letter only
			$code_entities_replace = array('','','','','','','','','', '','','','','','','','','','','','','','','','', '','','', '', '','','','','','',"",'','','','','','','','','','','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		break;		
	}
	
	$text = str_replace($code_entities_match, $code_entities_replace, $text);
	
	return $text;
}

function return_to_gamelist_link()
{
	global $user, $phpbb_root_path, $phpEx;;
	return '<br><br><a href="'.$phpbb_root_path.'games/index.'.$phpEx.'">'.$user->lang['RETURN_TO_GAMELIST'].'</a>';
}
  
function back_link()
{
	global $user;
	return '<br><br><a href="javascript:history.go(-1);">'.$user->lang['GO_BACK_LINK'].'</a>';
}

?>